<script setup>

import SlideViewSingle from "../component/slideview/SlideView.vue";
import {computed, ref} from "vue";
import {useErpUserStore} from "@/store/modules/usererp.js";
import ChieflyContacts from "@/views/crm/contacts/components/ChieflyContacts.vue";
import Activity from "@/views/crm/componentsNew/ActivityNew/index.vue";
import DetailHead from "@/views/scrm/component/detail/detailHead.vue";
import {crmCustomerReadAPI} from "@/api/crm/customer.js";
import {ElMessage} from "element-plus";
import {useTabsHandleHook} from "@/views/scrm/customer/detail/useTabsHandleHook.js";

defineOptions({
  // 客户管理 的 产品详情
  name: 'BusinessDetail',
})

const properties = defineProps({
  // 是否显示
  visible: Boolean,
  // 详情信息id，比如数据库中的id
  id: [String, Number],
  // 详情数据，最终会转换成optionData中的detailData
  detail: {},
  // 表示第几个详情，比如0-1-2
  pageIndex: [String, Number],
  // 用于详情切换
  pageList: Array,
})

const emits = defineEmits(['update:pageIndex', 'update:visible',
  'update:id', 'handle', 'hide-view'])

const optionData = reactive({
  // 详情数据
  detailData: {},
  crmType: "customer",
  // 是否展示重要联系人
  showImportInfo: true,
  // 当前的tab
  currentTabName: 'Activity',
  // 首要联系人
  firstContactsId: '',
})
const {detailData, crmType, showImportInfo, currentTabName} = toRefs(optionData)

// 当外部传入的detail发生改变的时候，需要立即更新本模块中的detailData属性
watch(() => properties.detail, (value) => {
  console.log("properties.detail", value)
  // 赋值本地的detailData
  optionData.detailData = value
  // 解析成业务需要的数据
  parseDetailData()
})

/**
 * 客户ID
 */
const customerId = computed(() => {
  return optionData.detailData ? optionData.detailData.customerId || '' : ''
})
const tabsHandleHook = useTabsHandleHook('customer', customerId.value);
const {showTabsNumber, tabOption, tabNames, getTabName, getTabsNum} = tabsHandleHook;

// 从store中拿到crm权限
const crm = computed(() => {
  const erpUserStore = useErpUserStore();
  return erpUserStore.crm
})

// 能否查看详情
const canShowDetail = computed(() => {
  if (optionData.detailData && optionData.detailData?.dataAuth === 0) {
    return false
  }

  return crm.value && crm.value[optionData.crmType] && crm.value[optionData.crmType].read
})


/**
 * 进入详情页面后的动作
 */
function onAfterEnter() {
  if (canShowDetail.value) {
    parseDetailData()
    tabsHandleHook.getTabsNum()
    // bus.on('crm-tab-num-update', getTabsNum)
  }
}

/**
 * 关闭
 */
function hideView() {
  emits('hide-view')
}

// 下面的headDetails、tabNames、activityHandle、getDetail需要自定义，不能放在SzDetail中
const headDetails = reactive([
  {title: '客户级别', value: ''},
  {title: '成交状态', value: ''},
  {title: '负责人', value: ''},
  {title: '更新时间', value: ''}
])

/**
 * 首要联系人添加
 */
function addChieflyContacts() {
  crmOption.createCRMType = 'contacts'
  crmOption.createActionInfo = {
    type: 'relative',
    crmType: optionData.crmType,
    data: {customer: detailData.value}
  }
}

/**
 * 根据记录筛选。只有存在Activity的时候，才需要logTypes
 */
const logTypes = computed(() => {
  return [
    {
      icon: 'all',
      color: '#2362FB',
      command: '',
      label: '全部活动'
    }, {
      icon: 'customer',
      color: '#487DFF',
      command: 2,
      label: '客户'
    }, {
      icon: 'o-task',
      color: '#D376FF',
      command: 11,
      label: '任务'
    }, {
      icon: 'business',
      color: '#FB9323',
      command: 5,
      label: '商机'
    }, {
      icon: 'contract',
      color: '#FD5B4A',
      command: 6,
      label: '合同'
    }, {
      icon: 'contacts',
      color: '#27BA4A',
      command: 3,
      label: '联系人'
    }, {
      icon: 'receivables',
      color: '#FFB940',
      command: 7,
      label: '回款'
    }, {
      icon: 'log',
      color: '#5864FF',
      command: 8,
      label: '日志'
    }, {
      icon: 'approve',
      color: '#9376FF',
      command: 9,
      label: '审批'
    }
  ]
})
// 是否能新建跟进记录
const canCreateFollowRecord = computed(() => {
  return crm.value && crm.value.followRecord && crm.value.followRecord.save
})

/**
 * 活动操作
 */
const activityHandle = computed(() => {
  let temps = [
    {
      type: 'task',
      label: '创建任务'
    }, {
      type: 'contacts',
      label: '创建联系人'
    }, {
      type: 'business',
      label: '创建商机'
    }, {
      type: 'contract',
      label: '创建合同'
    }, {
      type: 'receivables',
      label: '创建回款'
    }
  ]

  if (canCreateFollowRecord.value) {
    temps = [{
      type: 'log',
      label: '写跟进'
    }].concat(temps)
  }

  return temps
})


/**
 * 详情，根据传入的detail接口数据，解析到业务需要的数据
 */
function parseDetailData() {
  optionData.firstContactsId = ''
  optionData.detailData = properties.detail
  console.log("firstContactsId", optionData.firstContactsId)

  optionData.firstContactsId = optionData.detailData.contactsId
  headDetails[0].value = optionData.detailData.level

  const dealItem = headDetails[1]
  if (optionData.detailData.dealStatus === null
      || optionData.detailData.dealStatus === ''
      || optionData.detailData.dealStatus === undefined) {
    dealItem.showIcon = false
    dealItem.value = ''
  } else {
    dealItem.showIcon = true
    if (optionData.detailData.dealStatus == 1) {
      dealItem.icon = 'wk wk-success deal-suc'
      dealItem.style = {
        fontSize: '14px',
        color: '#20b559',
        marginRight: '3px'
      }
      dealItem.value = '已成交'
    } else {
      dealItem.icon = 'wk wk-close deal-un'
      dealItem.style = {
        fontSize: '14px',
        color: '#f95a5a',
        marginRight: '3px'
      }
      dealItem.value = '未成交'
    }
  }

  headDetails[2].title = '负责人'
  headDetails[2].value = optionData.detailData.ownerUserName
  headDetails[3].value = optionData.detailData.updateTime
}


/**
 * 详情页面切换
 */
function pageChange(type) {
  let currentPageIndex = properties.pageIndex
  if (type === 'prev') { //上一个
    if (properties.pageIndex > 0) {
      emits('update:pageIndex', --currentPageIndex)
      emits('update:id', properties.pageList[currentPageIndex][`${optionData.crmType}Id`])
    } else {
      ElMessage.error({message: '没有更多了！'})
    }
  } else if (type === 'next') { // 下一个
    if (currentPageIndex < properties.pageList.length - 1) {
      emits('update:pageIndex', ++currentPageIndex)
      emits('update:id', properties.pageList[currentPageIndex][`${optionData.crmType}Id`])
    } else {
      ElMessage.error({message: '没有更多了！'})
    }
  }
}

// 编辑操作
const showEditDialog = ref(false)

/**
 * 顶部头 操作
 * @param {*} data
 */
function detailHeadHandle(data) {
  // 返回值为false 不继续执行
  if (detailHeadHandleClick(data) === false) {
    return
  }

  if (data.type === 'edit') {
    showEditDialog.value = true
  } else if (data.type === 'delete' ||
      data.type === 'exit-team' ||
      data.type === 'alloc' ||
      data.type === 'get' ||
      data.type === 'transfer' ||
      data.type === 'transform' ||
      data.type === 'delete' ||
      data.type === 'put_seas') {
    hideView()
  } else if (data.type === 'state_start' ||
      data.type === 'state_disable' ||
      data.type === 'deal_status' ||
      data.type === 'cancel' ||
      data.type === 'examine') {
    parseDetailData()
  } else if (data.type === 'save-success') {
    // 但字段编辑成功刷新
    editSaveSuccess()
    return
  }

  emits('handle', data)
}

function editSaveSuccess() {
  emits('crm-detail-update', crmOption.crmType)
  emits('handle', {type: 'save-success'})
  optionData.detailData = null
  parseDetailData()
}

/**
 * 顶部头 操作
 * @param {*} data
 */
function detailHeadHandleClick(data) {
  // if (data.type === 'edit') {
  //   crmOption.createCRMType = 'customer'
  //   createActionInfo.value = {
  //     type: 'update',
  //     id: props.id,
  //     batchId: detailData.value.batchId
  //   }
  //   isCreate.value = true
  //   return false
  // }
}

</script>

<template>
  <SlideViewSingle v-if="id && visible" :body-style="{padding: 0, height: '100%'}"
                   class="d-view"
                   @afterEnter="onAfterEnter"
                   @close="hideView">
    <template v-slot:default>
      <div ref="crmDetailMain" class="detail-main">
        <flexbox v-if="canShowDetail && detailData" direction="column" align="stretch" class="d-container">
          <!--详情的头部-->
          <DetailHead :detail="detailData" :detail-head="headDetails"
                      :id="id"
                      :page-list="pageList"
                      @pageChange="pageChange"
                      @handle="detailHeadHandle"
                      @close="hideView"/>
          <!--详情的Tab页面-->
          <flexbox class="d-container-bd" align="stretch">
            <el-tabs v-model="currentTabName" type="border-card" class="d-container-bd--left">
              <el-tab-pane v-for="(item, index) in tabNames" :key="index"
                           :label="item.label" :name="item.name" lazy>
                <component :is="item.comp"
                           :detail="detailData"
                           :type-list="logTypes"
                           :handle="activityHandle"
                           :id="id"
                           :crm-type="crmType"
                           @handle="detailHeadHandle"/>
              </el-tab-pane>
            </el-tabs>
            <transition name="slide-fade">
              <el-tabs v-show="showImportInfo" model-value="chiefly-contacts" type="border-card"
                       class="d-container-bd--right">
                <el-tab-pane label="重要信息" name="chiefly-contacts" lazy>
                  <ChieflyContacts :id="id" crm-type="customer" :customer-id="customerId" @add="addChieflyContacts"/>
                </el-tab-pane>
              </el-tabs>
            </transition>
          </flexbox>
        </flexbox>
      </div>
      <el-button class="first-button" @click="showImportInfo= !showImportInfo">
        重<br>要<br>信<br>息<br>
        <i :class="{ 'is-reverse': !showImportInfo }" class="el-icon-arrow-right el-icon--right"/>
      </el-button>
    </template>
  </SlideViewSingle>
</template>

<style scoped lang="scss">
.image {
  color: #333;

  &-info {
    margin: 10px 25px 0;

    &__label {
      font-size: 13px;
    }

    &__list {
      overflow-x: auto;
      white-space: nowrap;

      img {
        margin-top: 15px;
        border-radius: $xr-border-radius-base;
        cursor: pointer;
      }

      img + img {
        margin-left: 20px;
      }

      .main-img {
        width: 100px;
        height: 76px;
        object-fit: contain;
        vertical-align: top;
      }

      .detial-img {
        width: 100px;
        height: 80px;
        object-fit: contain;
        vertical-align: top;
      }
    }
  }

  .no-img {
    color: #666;
    margin: 50px 0;
    text-align: center;
  }
}

@import 'detail/crmdetail';
.busi-state-main {
  margin-top: 15px;
  padding: 15px;
  border-top: 1px solid $xr-border-line-color;
  border-bottom: 1px solid $xr-border-line-color;
  background-color: white;
}

.busi-state {
  position: relative;
  padding-left: 20px;
  overflow-x: auto;
  overflow-y: hidden;
  z-index: 1;

  a {
    flex-shrink: 0;
  }
}

.busi-state-item {
  padding: 10px 30px;
  margin: 5px 0;
  height: 38px;
  position: relative;
  margin-right: 5px;
  border-top: 2px solid #ebebeb;
  border-bottom: 2px solid #ebebeb;

  .state-circle {
    width: 38px;
    height: 38px;
    border-radius: 19px;
    background-color: white;
    transform: rotate(45deg);
    position: absolute;
    z-index: -1;
  }

  .state-arrow {
    width: 38px;
    height: 38px;
    transform: scale(0.707) rotate(45deg);
    border-top: 2px solid #ebebeb;
    border-right: 2px solid #ebebeb;
    background-color: white;
    position: absolute;
  }
}

.state-undo {
  border-top: 2px solid #ebebeb;
  border-bottom: 2px solid #ebebeb;
  background-color: white;
  color: #666;

  .state-circle {
    border-color: #ebebeb;
    background-color: white;
  }

  .state-arrow {
    border-color: #ebebeb;
    background-color: white;
  }
}

.state-doing {
  border-top: 2px solid #00CA9D;
  border-bottom: 2px solid #00CA9D;
  background-color: white;
  color: #00CA9D;

  .circle-left {
    border-color: #00CA9D;
    background-color: white;
  }

  .circle-right {
    border-color: #00CA9D;
    background-color: white;
  }

  .arrow-left {
    border-color: #00CA9D;
    background-color: white;
  }

  .arrow-right {
    border-color: #00CA9D;
    background-color: white;
  }
}

.state-suc {
  border-top: 2px solid #00CA9D;
  border-bottom: 2px solid #00CA9D;
  background-color: #00CA9D;
  color: white;

  .circle-left {
    border-color: #00CA9D;
    background-color: #00CA9D;
  }

  .circle-right {
    border-color: #00CA9D;
    background-color: #00CA9D;
  }

  .arrow-left {
    border-color: #00CA9D;
    background-color: white;
  }

  .arrow-right {
    border-color: #00CA9D;
    background-color: #00CA9D;
  }
}

.state-fail {
  border-top: 2px solid #ff6767;
  border-bottom: 2px solid #ff6767;
  background-color: #ff6767;
  color: white;

  .circle-left {
    border-color: #ff6767;
    background-color: #ff6767;
  }

  .circle-right {
    border-color: #ff6767;
    background-color: #ff6767;
  }

  .arrow-left {
    border-color: #ff6767;
    background-color: white;
  }

  .arrow-right {
    border-color: #ff6767;
    background-color: #ff6767;
  }
}

.state-invalid {
  border-top: 2px solid #ebebeb;
  border-bottom: 2px solid #ebebeb;
  background-color: #ebebeb;
  color: #666;

  .state-circle {
    border-color: #ebebeb;
    background-color: #ebebeb;
  }

  .state-arrow {
    border-color: #ebebeb;
    background-color: #ebebeb;
  }

  .circle-left {
    border-color: #ebebeb;
    background-color: #ebebeb;
  }

  .circle-right {
    border-color: #ebebeb;
    background-color: #ebebeb;
  }

  .arrow-left {
    border-color: #ebebeb;
    background-color: white;
  }

  .arrow-right {
    border-color: #ebebeb;
    background-color: #ebebeb;
  }
}

.arrow-right {
  z-index: 1;
  top: -2px;
  right: -19px;
}

.arrow-left {
  top: -2px;
  left: -18px;
}

.circle-right {
  border-top: 2px solid #ebebeb;
  border-right: 2px solid #ebebeb;
  z-index: 1;
  top: -2px;
  right: -15.5px;
}

.circle-left {
  border-left: 2px solid #ebebeb;
  border-bottom: 2px solid #ebebeb;
  top: -2px;
  left: -17px;
}

/** 状态操作布局 */
.state-handel-cont {
  font-size: 13px;
  color: #333;

  .state-handel-item {
    padding: 10px 0;
    cursor: pointer;

    .state-handel-item-img {
      width: 16px;
      height: 16px;
      border-radius: 8px;
      margin-right: 8px;
      flex-shrink: 0;
      display: block;
    }

    .state-handel-item-name {
      flex: 1;
    }

    .state-handel-item-value {
      flex-shrink: 0;
    }
  }

  .state-handel-item:hover {
    background-color: #f7f8fa;
  }
}

</style>